package com.yangfan.juc.locks;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description: 读写锁
 * @author: yangfan
 * @date: Created in 2020/3/27 0027 9:55
 * @modified By:
 */
public class ReentrantReadWriteLockExample {

    private static List<Long> data = new ArrayList<>();

    private static  ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static final Lock READ_LOCK = readWriteLock.readLock();

    private static final Lock WRITE_LOCK = readWriteLock.writeLock();


    public static void main(String[] args) throws InterruptedException {


        Thread t1 = new Thread(() -> write());
        t1.start();


        TimeUnit.MILLISECONDS.sleep(5);


        Thread t2 = new Thread(() -> read());
        t2.start();


    }



    public static void read(){
        try {
            READ_LOCK.lock();
            System.out.println(Thread.currentThread().getName() + "读取数据");
            data.forEach( x -> System.out.println(x));
        }finally {
            READ_LOCK.unlock();
        }
    }

    public static void write(){

        try {
            WRITE_LOCK.lock();
            System.out.println(Thread.currentThread().getName() + "写入数据");
            int i = 1;
            while (i <= 5){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
            data.add(System.currentTimeMillis());
        }finally {
            WRITE_LOCK.unlock();
        }
    }


}
